//
//  FoodListViewController.m
//  FaceRecognition
//
//  Created by syun on 2018/1/31.
//  Copyright © 2018年 Sylar. All rights reserved.
//

#import "FoodListViewController.h"
#import "FoodListTableViewCell.h"
#import "FoodListModel.h"
#import "FoodListLeftTableViewCell.h"
@interface FoodListViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSArray * leftArray;
    NSString * currentTimeString;
    NSInteger _selectIndex;
    NSInteger _leftSelectIndex;
    BOOL _isScrollDown;
    int weekCount;
    NSInteger currentWeek;
   
   NSMutableArray * dataArray1;
   NSMutableArray * dataArray2;
   NSMutableArray * dataArray3;
   NSMutableArray * dataArray4;
   NSMutableArray * dataArray5;
   NSMutableArray * dataArray6;
   NSMutableArray * dataArray7;
   
}
@property (nonatomic, strong) UITableView * rightTableView;
@property (nonatomic, strong) UITableView * leftTableView;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) NSMutableArray * sectionArray;
@property (nonatomic, strong) NSMutableArray * buttonArray;

@end

@implementation FoodListViewController



- (NSMutableArray *)buttonArray
{
   if (_buttonArray == nil) {
      
      _buttonArray = [NSMutableArray array];
   }
   
   return _buttonArray;
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    
    return _dataArray;
}

- (NSMutableArray *)sectionArray
{
    if (_sectionArray == nil) {
        
        _sectionArray = [NSMutableArray array];
    }
    
    return _sectionArray;
}

- (UITableView *)leftTableView
{
    if (_leftTableView == nil) {
        
        _leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, 130, SCREENHEIGH-SafeAreaTopHeight - SafeAreaBottomHeight-70) style:UITableViewStylePlain];
        _leftTableView.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    return _leftTableView;
}
- (UITableView *)rightTableView
{
    if (_rightTableView == nil) {
        
        _rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(131, SafeAreaTopHeight, SCREENWIDTH-131, SCREENHEIGH - SafeAreaTopHeight-SafeAreaBottomHeight-70) style:UITableViewStylePlain];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    return _rightTableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.nav_titleLabel.text = @"每日食谱";
    self.view.backgroundColor = [UIColor whiteColor];
    leftArray = @[@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六",@"星期日",];
    weekCount = 0;
    _leftSelectIndex = 0;
    
    currentTimeString = [self getCurrentTimes];
    [self getCurrentWeek];//获取星期几对应左列表默认选中
    [self requestFoodListData:currentTimeString];
    
    [self.view addSubview:self.leftTableView];
    [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:_leftSelectIndex inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    
    [self.view addSubview:self.rightTableView];
    
    [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_leftSelectIndex] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    [self BottomUI];
    // Do any additional setup after loading the view.
}

- (void)BottomUI
{
    UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENHEIGH - 70 - SafeAreaBottomHeight, SCREENWIDTH, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"dedede"];
    [self.view addSubview:line];
    
    NSArray * arr = @[@"上一周",@"本周",@"下一周"];
    
    float w = SCREENWIDTH/3;
    
    for (int i = 0; i < 3;  i++) {
        
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(w*i,SCREENHEIGH - 69 - SafeAreaBottomHeight, w, 69);
        [button setTitle:[arr objectAtIndex:i] forState:UIControlStateNormal];
       
        button.tag = i + 50;
        if (i ==0 || i == 2) {
            
             [button setTitleColor:[UIColor colorWithHexString:@"7c7d7b"] forState:UIControlStateNormal];
        }else
        {
           [button setTitleColor:[UIColor colorWithHexString:@"4c4e4c"]forState:UIControlStateNormal];
        }
        [button addTarget:self action:@selector(changeDateAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [self.buttonArray addObject:button];
    }
}

- (void)changeDateAction:(UIButton *)sender
{
    NSInteger tag = sender.tag - 50;
   
   for (UIButton * btn in self.buttonArray) {
      
      if (btn.tag == sender.tag) {
         
         [btn setTitleColor:[UIColor colorWithHexString:@"4c4e4c"] forState:UIControlStateNormal];
      }else
      {
         [btn setTitleColor:[UIColor colorWithHexString:@"7c7d7b"] forState:UIControlStateNormal];
      }
   }
   
   
    if(tag == 2)
    {
        weekCount = 1;
        _leftSelectIndex = 0;
        
    }else if (tag == 0)
    {
        weekCount = -1;
        _leftSelectIndex = 0;
        
    }else
    {
        weekCount = 0;
        [self getCurrentWeek];
    }
    
    [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:_leftSelectIndex inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    
     [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_leftSelectIndex] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    
    NSString * dateString = [self getDesignatedDate];
    
    [self requestFoodListData:dateString];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _leftTableView) {
        
        return 1;
        
    }else
    {
        return 7;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _leftTableView) {
        
        return 7;
        
    }else
    {
       return 5;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        
        return 80;
        
    }else{
        
        return 130;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _rightTableView) {
        
        return 60;
    }else
    {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    FoodListModel * model = [self.sectionArray objectAtIndex:section];
    if (tableView == _rightTableView) {
        
        UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH-131, 50)];
        backView.backgroundColor = [UIColor whiteColor];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(15, 22,SCREENWIDTH - 160, 16)];
        label.font = [UIFont systemFontOfSize:16];
        
        NSString * dateStr;

        NSLog(@"model.date = %@",model.date);
        if (model.date.length > 10) {  //2016-07-23 09:12
            dateStr = [model.date substringToIndex:10];
            
             NSLog(@"model.date = %@",dateStr);
        }
        
        NSString * titleStr = [NSString stringWithFormat:@"%@(%@)",[leftArray objectAtIndex:section],dateStr];
        
        if ([dateStr isEqualToString:currentTimeString]) {
            
            label.text = [NSString stringWithFormat:@"今天(%@)",dateStr];
            label.textColor = [UIColor colorWithHexString:@"fe7d52"];
            
        }else
        {
            label.text = titleStr;
            label.textColor = [UIColor colorWithHexString:@"2a312b"];
        }
        
        [backView addSubview:label];
        
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, 59,SCREENWIDTH- 131, 1)];
        line.backgroundColor = [UIColor colorWithHexString:@"dedede"];
        [backView addSubview:line];
        
        return backView;
        
    }else
    {
        return nil;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(tableView == _leftTableView)
    {
        
        FoodListLeftTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"FoodListLeftTableViewCell"];
        if (cell == nil) {
            
            cell = [[FoodListLeftTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FoodListLeftTableViewCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }


        if (indexPath.row == _leftSelectIndex) {
            
            cell.leftLable.hidden = NO;
            cell.rightLabel.textColor = [UIColor orangeColor];
            cell.contentView.backgroundColor = [UIColor whiteColor];
        }else
        {
            cell.leftLable.hidden = YES;
            cell.rightLabel.textColor = [UIColor blackColor];
            cell.contentView.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
        }
        
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, 79, 130, 1)];
        line.backgroundColor = [UIColor colorWithHexString:@"dedede"];
        [cell.contentView addSubview:line];
        
        cell.rightLabel.text = [leftArray objectAtIndex:indexPath.row];
        
         return cell;
        
    }else
    {
       
        FoodListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"FoodListTableViewCell"];
        if (cell == nil) {
            
            cell = [[FoodListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FoodListTableViewCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (indexPath.section == 0) {
            
            FoodListModel * model = [dataArray1 objectAtIndex:indexPath.row ];
            cell.foodTypeLable.text = model.foodtypename;
            cell.foodNameLable.text = model.foodname;
            
            NSString * imageStr = [NSString stringWithFormat:@"%@%@",PICPERFIXURL,model.foodpic];
            NSLog(@"imageStr = %@",imageStr);
            [cell.foodImage sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"foodbackImage"]];
            

        }else if (indexPath.section ==1)
        {
            FoodListModel * model = [dataArray2 objectAtIndex:indexPath.row ];
            cell.foodTypeLable.text = model.foodtypename;
            cell.foodNameLable.text = model.foodname;
            [cell.foodImage sd_setImageWithURL:[NSURL URLWithString:model.foodpic] placeholderImage:[UIImage imageNamed:@"foodbackImage"]];
            
        }else if (indexPath.section ==2)
        {
            FoodListModel * model = [dataArray3 objectAtIndex:indexPath.row ];
            cell.foodTypeLable.text = model.foodtypename;
            cell.foodNameLable.text = model.foodname;
            [cell.foodImage sd_setImageWithURL:[NSURL URLWithString:model.foodpic] placeholderImage:[UIImage imageNamed:@"foodbackImage"]];
            
        }else if (indexPath.section ==3)
        {
            FoodListModel * model = [dataArray4 objectAtIndex:indexPath.row ];
            cell.foodTypeLable.text = model.foodtypename;
            cell.foodNameLable.text = model.foodname;
            
            NSString * imageStr = [NSString stringWithFormat:@"%@%@",PICPERFIXURL,model.foodpic];
            [cell.foodImage sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"foodbackImage"]];
            
        }else if (indexPath.section ==4)
        {
            FoodListModel * model = [dataArray5 objectAtIndex:indexPath.row ];
            cell.foodTypeLable.text = model.foodtypename;
            cell.foodNameLable.text = model.foodname;
            
            NSString * imageStr = [NSString stringWithFormat:@"%@%@",PICPERFIXURL,model.foodpic];
            [cell.foodImage sd_setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"foodbackImage"]];
            
        }else if (indexPath.section ==5)
        {
            FoodListModel * model = [dataArray6 objectAtIndex:indexPath.row ];
            cell.foodTypeLable.text = model.foodtypename;
            cell.foodNameLable.text = model.foodname;
            [cell.foodImage sd_setImageWithURL:[NSURL URLWithString:model.foodpic] placeholderImage:[UIImage imageNamed:@"foodbackImage"]];
            
        }else
        {
            FoodListModel * model = [dataArray7 objectAtIndex:indexPath.row ];
            cell.foodTypeLable.text = model.foodtypename;
            cell.foodNameLable.text = model.foodname;
            [cell.foodImage sd_setImageWithURL:[NSURL URLWithString:model.foodpic] placeholderImage:[UIImage imageNamed:@"foodbackImage"]];
        }
        
        return cell;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (_leftTableView == tableView)
    {
        _selectIndex = indexPath.row;
        
        [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_selectIndex] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        _leftSelectIndex = _selectIndex;
        
        [self.leftTableView reloadData];
        
    }
}

// 标记一下 RightTableView 的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat lastOffsetY = 0;
    
    UITableView *tableView = (UITableView *) scrollView;
    if (_rightTableView == tableView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

// TableView 分区标题即将展示
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section
{
    // 当前的 tableView 是 RightTableView，RightTableView 滚动的方向向上， RightTableView 是用户拖拽而产生滚动的（（主要判断 RightTableView 用户拖拽而滚动的，还是点击 LeftTableView 而滚动的）
    if ((_rightTableView == tableView) && !_isScrollDown && _rightTableView.dragging)
    {
        [self selectRowAtIndexPath:section];
    }
}

// TableView 分区标题展示结束
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // 当前的 tableView 是 RightTableView，RightTableView 滚动的方向向下， RightTableView 是用户拖拽而产生滚动的（主要判断 RightTableView 用户拖拽而滚动的，还是点击 LeftTableView 而滚动的）
    if ((_rightTableView == tableView) && _isScrollDown && _rightTableView.dragging)
    {
        [self selectRowAtIndexPath:section + 1];
    }
}

// 当拖动右边 TableView 的时候，处理左边 TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    
    _leftSelectIndex = index;
    
    [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    [self.leftTableView reloadData];

    
}

-(NSString*)getCurrentTimes{

    //得到当前的时间
    NSDate * mydate = [NSDate date];
    
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentTimeString = [dateFormatter stringFromDate:mydate];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;

    
}

- (void)getCurrentWeek
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDate *now;
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday;
    
    now=[NSDate date];
    
    comps = [calendar components:unitFlags fromDate:now];
    
    NSInteger week = [comps weekday];
    
    switch (week) {
        case 1:
            _leftSelectIndex = 6;
            break;
        case 2:
            _leftSelectIndex = 0;
            break;
        case 3:
            _leftSelectIndex = 1;
            break;
        case 4:
            _leftSelectIndex = 2;
            break;
        case 5:
            _leftSelectIndex = 3;
            break;
        case 6:
            _leftSelectIndex = 4;
            break;
        case 7:
            _leftSelectIndex = 5;
            break;
            
        default:
            break;
    }

}
- (NSString *)getDesignatedDate
{
    //得到当前的时间
    NSDate * mydate = [NSDate date];
    
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *comps = nil;
    
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:mydate];
    
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setDay:7 * weekCount];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
    NSString *beforDate = [dateFormatter stringFromDate:newdate];
    
    return beforDate;
}

- (void)requestFoodListData:(NSString *)date
{
    RequestParam * param = [RequestParam param];
    
    NSString * schoolid = [SYAccountTool ShareAccount].account.scid;
    if (schoolid) {
        
        param.scid = schoolid;
    }
    param.date = date;
    param.method = @"api_food_list";
    [Utils get:nil parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
       
        [self.sectionArray removeAllObjects];
        
        NSArray * arr = [jsonObject objectForKey:@"re_data"];
        NSLog(@"arr = %@",arr);
       
       dataArray1 = [NSMutableArray array];
       dataArray2 = [NSMutableArray array];
       dataArray3 = [NSMutableArray array];
       dataArray4 = [NSMutableArray array];
       dataArray5 = [NSMutableArray array];
       dataArray6 = [NSMutableArray array];
       dataArray7 = [NSMutableArray array];
       
        for (int i = 0 ;i < arr.count; i++) {
            
            NSDictionary * dic = [arr objectAtIndex:i];
            
            FoodListModel * model = [FoodListModel mj_objectWithKeyValues:dic];
           
           NSInteger week = [model.week integerValue];
           
           switch (week) {
              case 1:
                 [dataArray1 addObject:model];
                 break;
              case 2:
                 [dataArray2 addObject:model];
                 break;
              case 3:
                 [dataArray3 addObject:model];
                 break;
              case 4:
                 [dataArray4 addObject:model];
                 break;
              case 5:
                 [dataArray5 addObject:model];
                 break;
              case 6:
                 [dataArray6 addObject:model];
                 break;
              case 7:
                 [dataArray7 addObject:model];
                 break;

              default:
                 break;
           }
            
            int L = i%5;
            
            if (L == 0) {
                
                [self.sectionArray addObject:model];
            }
        }
        [_leftTableView reloadData];
        [_rightTableView reloadData];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
